﻿var ws: WebSocket | null = null;
var connect: boolean = false;
var stattxt: HTMLSpanElement;
var statusr: HTMLSpanElement;
var statmsg: HTMLSpanElement;
var lastmsgid: number = 0;
var lastmsg: { [id: number]: any } = {}
var myguid: string;
var users: { [id: string]: string } = {};
var listusr: HTMLDivElement;
var listmsg: HTMLDivElement;

function updatestat() {
    stattxt.textContent = "AnyChat connect=" + connect;
    statmsg.textContent = "last msg id=" + lastmsgid;
    statusr.textContent = "myname:" + users[myguid];
    for (var i = listusr.childElementCount - 1; i >= 0; i--) {
        var node = listusr.children[i];
        node.remove();
    }
    for (var u in users) {
        addinfotolist(listusr, users[u]);
    }

    for (var i = listmsg.childElementCount - 1; i >= 0; i--) {
        var node = listmsg.children[i];
        node.remove();
    }
    var keys = Object.keys(lastmsg).reverse();
    for (var k in keys) {
        var u = keys[k];
        addinfotolist(listmsg, "id=" + u + ": " + lastmsg[u]);
    }

}

function addinfo(log: string) {
    var span = document.createElement("span");
    span.textContent = log;
    var br = document.createElement("br");
    document.body.appendChild(span);
    document.body.appendChild(br);
    return span
}
function addbtn(str: string, event: () => void) {
    var btn = document.createElement("button");
    btn.textContent = str;
    btn.onclick = event;
    var br = document.createElement("br");
    document.body.appendChild(btn);
    document.body.appendChild(br);
}

function addinputgroup(str: string, event: (txt) => void) {
    var span = document.createElement("span");
    var input = document.createElement("input");
    var btn = document.createElement("button");
    var br = document.createElement("br");
    span.textContent = str;
    input.type = "input";
    btn.textContent = "ok";
    btn.onclick = () => {
        if (input.value == "")
            return;
        event(input.value);
    }
    document.body.appendChild(span);
    document.body.appendChild(input);
    document.body.appendChild(btn);
    document.body.appendChild(br);
}
function addFixSizeDiv(width: number, height: number): HTMLDivElement {
    var div = document.createElement("div");
    if (width > 0)
        div.style.width = width + "px";
    if (height > 0)
        div.style.height = height + "px";
    div.style.overflow = "scroll";
    div.style.borderStyle = "double";

    var br = document.createElement("br");
    document.body.appendChild(div);
    document.body.appendChild(br);
    return div;
}

function addinfotolist(div: HTMLDivElement, log: string) {
    var span = document.createElement("span");
    span.textContent = log;
    var br = document.createElement("br");
    div.appendChild(span);
    div.appendChild(br);
    return span
}
function initwebsocket() {

    ws = new WebSocket("ws://localhost:1988/ws");

    ws.onopen = (ev) => {
        console.log("onopen");
        connect = true;
        lastmsgid = 0;
        updatestat();
        //addText("websocket onopen");
    }
    ws.onerror = (ev) => {
        console.log("onerror" + ev);
        connect = false;
        lastmsgid = 0;
        updatestat();
    }
    ws.onclose = (ev) => {
        console.log("onclose");
        connect = false;
        lastmsgid = 0;
        updatestat();
    }
    ws.onmessage = (ev) => {
        if (typeof ev.data == "string") {
            //收到文本数据
            var result = ev.data as string;

            var json = JSON.parse(result);
            if (json["cmd"] == "userin") {
                var guid = json["guid"];
                var name = json["name"];
                var self = json["self"];
                users[guid] = name;
                if (self) {
                    myguid = guid;
                }
                addinfotolist(listusr, name);
                console.log("userin " + guid + "," + name + "," + self);
            }
            else if (json["cmd"] == "userexit") {
                var guid = json["guid"];
                delete users[guid];
                console.log("userexit " + guid);
            }
            else if (json["cmd"] == "msg") {
                var msgid = json["msgid"];
                var msg = json["msg"];
                if (msgid > lastmsgid)
                    lastmsgid = msgid;
                lastmsg[msgid] = msg;
                var keys = Object.keys(lastmsg);
                if (keys.length > 20) {
                    delete lastmsg[keys[0]];
                }
                console.log("msg " + msgid + "," + msg);
            }
            else if (json["cmd"] == "msgid") {
                var msgid = json["msgid"];
                lastmsgid = parseInt(msgid);
                console.log("msgid " + msgid);
            }
            else {
                console.log("onmessage:" + result);
            }
        }
        else if (ev.data instanceof Blob) {
            console.log("onmessage bin:");
            ////收到2进制数据
            //var blob: Blob = ev.data as Blob;
            //var reader = new FileReader();
            //reader.onloadend = (ev2) => {
            //    var u8 = new Uint8Array(reader.result as ArrayBuffer);
            //    var text = Bytes2String(u8);
            //    console.log("onmessage:" + text);
            //    addText("websocket onmessage(bin):" + text);
            //};
            //reader.readAsArrayBuffer(blob);

        }
        updatestat();
    }

}


function start() {

    initwebsocket();
    //定时刷msgid
    setInterval(() => {
        if (connect) {
            var sendobj = { cmd: "getmsgid" };
            ws?.send(JSON.stringify(sendobj));
        }
    }, 3000);
    stattxt = addinfo("any chat");
    statmsg = addinfo("last msg id");
    addbtn("get all user", () => {
        if (connect) {
            var sendobj = { cmd: "getallusr" };
            ws?.send(JSON.stringify(sendobj));
        }
    });
    //得到最后20条
    addbtn("get last 20 msg", () => {
        var i = lastmsgid - 20;
        if (i < 1) i = 1;
        for (var n = i; n <= lastmsgid; n++) {
            var sendobj = {
                cmd: "getmsg", msgid: n.toString()
            };
            ws?.send(JSON.stringify(sendobj));
        }
    });
    statusr = addinfo("myinfo");
    addinputgroup("setname", (txt) => {
        if (connect) {
            var sendobj = { cmd: "setname", name: txt };
            ws?.send(JSON.stringify(sendobj));
        }
    });
    listusr = addFixSizeDiv(0, 150);

    //addbtn("getlastmsgid", () => {
    //    if (connect) {
    //        var sendobj = { cmd: "getmsgid" };
    //        ws?.send(JSON.stringify(sendobj));
    //    }
    //});
    addinputgroup("sendmsg", (txt) => {
        if (connect) {
            var sendobj = {
                cmd: "sendmsg", msg: { "txt": txt }
            };
            ws?.send(JSON.stringify(sendobj));
        }
    });

    listmsg = addFixSizeDiv(0, 500);

}

window.onload = start;